<template>
  <el-form
    :model="form"
    label-width="80px"
    ref="form"
    :rules="rules"
    @submit.native.prevent
    label-position="left"
  >
  
    <el-form-item label="姓名" prop="name" required>
      <el-input v-model="form.name" :disabled="!isEditable" />
    </el-form-item>
    
    <el-form-item label="性别" prop="gender" required>
      <el-select v-model="form.gender" :disabled="!isEditable">
        <el-option label="男" value="男" />
        <el-option label="女" value="女" />
      </el-select>
    </el-form-item>
    
    <el-form-item label="年龄" prop="age" required>
      <el-select
        v-model="form.age"
        placeholder="请选择年龄"
        :disabled="!isEditable"
      >
        <el-option
          v-for="age in ageOptions"
          :key="age"
          :label="age"
          :value="age"
        />
      </el-select>
    </el-form-item>
    
    <el-form-item label="图片" prop="picture" required>
      <el-upload
        class="avatar-uploader"
        action="http://localhost:8080/resume/upload"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
        :disabled="!isEditable"
      >
        <el-image
          style="width: 100px; height: 100px"
          :src="form.picture"
          :fit="fit"
        />
      </el-upload>
    </el-form-item>
    
    <el-form-item label="电话号码" prop="phoneNumber" required>
      <el-input v-model="form.phoneNumber" :disabled="!isEditable" />
    </el-form-item>
    
    <el-form-item label="邮箱" prop="email" required>
      <el-input v-model="form.email" :disabled="!isEditable" />
    </el-form-item>
<!-- aiFields: [
        { key: "intention", label: "求职意向", textarea: false },
        { key: "abilities", label: "能力", textarea: true },
        { key: "background", label: "教育背景", textarea: true },
        { key: "experience", label: "工作经验", textarea: true },
      ], -->
    <template v-for="field in aiFields">
      <el-form-item :key="field.key + '-buttons'">
        <el-button-group>
          <el-button
            size="mini"
            type="primary"
            @click="requestAi(field.key, 'polish')"
            >AI 润色</el-button
          >
          <el-button
            size="mini"
            type="warning"
            @click="requestAi(field.key, 'expand')"
            >AI 扩写</el-button
          >
          <el-button
            size="mini"
            type="info"
            @click="requestAi(field.key, 'shrink')"
            >AI 缩写</el-button
          >
        </el-button-group>
      </el-form-item>
      
      <el-form-item
        :key="field.key + '-input'"
        :label="field.label"
        :prop="field.key"
        required
      >
        <el-input
          v-model="form[field.key]"
          :type="field.textarea ? 'textarea' : 'text'"
          :rows="field.textarea ? 4 : null"
          :disabled="!isEditable"
        />
      </el-form-item>
      <div
        v-if="aiSuggestions[field.key]"
        :key="field.key + '-suggestion'"
        class="ai-suggestion"
      >
        <div class="original">原文：{{ form[field.key] }}</div>
        <div class="suggestion">AI 建议：{{ aiSuggestions[field.key] }}</div>
        <el-button size="mini" @click="applySuggestion(field.key, 'append')"
          >追加</el-button
        >
        <el-button
          size="mini"
          type="primary"
          @click="applySuggestion(field.key, 'replace')"
          >替换</el-button
        >
      </div>
    </template>

    <el-form-item>
      <el-button type="primary" @click="isEditable = true">编辑</el-button>
      <el-button type="success" @click="updateForm">完成并预览模板</el-button>
      <el-button type="danger" @click="deleteForm">删除简历</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import axios from "axios";
export default {
  props: {
    defaultForm: { type: Object, default: () => ({}) },
  },
  data() {
    return {
      form: {
        name: this.defaultForm.name || "",
        gender: this.defaultForm.gender || "未填写",
        age: this.defaultForm.age || null,
        picture: this.defaultForm.picture || "",
        phoneNumber: this.defaultForm.phoneNumber || "",
        email: this.defaultForm.email || "",
        intention: this.defaultForm.intention || "",
        abilities: this.defaultForm.abilities
          ? this.defaultForm.abilities.join("\n")
          : "",
        background: this.defaultForm.background || "",
        experience: this.defaultForm.experience
          ? this.defaultForm.experience.join("\n")
          : "",
      },
      aiFields: [
        { key: "intention", label: "求职意向", textarea: false },
        { key: "abilities", label: "能力", textarea: true },
        { key: "background", label: "教育背景", textarea: true },
        { key: "experience", label: "工作经验", textarea: true },
      ],
      aiSuggestions: {},
      ageOptions: Array.from({ length: 53 }, (_, i) => i + 18),
      isEditable: false,
      loading: {}, // 新增loading状态
      rules: {
        name: [{ required: true, message: "请填写姓名", trigger: "blur" }],
        gender: [{ required: true, message: "请选择性别", trigger: "change" }],
        age: [{ required: true, message: "请选择年龄", trigger: "change" }],
        picture: [{ required: true, message: "请上传图片", trigger: "blur" }],
        phoneNumber: [
          { required: true, message: "请填写电话号码", trigger: "blur" },
        ],
        email: [{ required: true, message: "请填写邮箱", trigger: "blur" }],
        intention: [
          { required: true, message: "请填写求职意向", trigger: "blur" },
        ],
        abilities: [
          { required: true, message: "请填写个人能力", trigger: "blur" },
        ],
        background: [
          { required: true, message: "请填写教育背景", trigger: "blur" },
        ],
        experience: [
          { required: true, message: "请填写工作经历", trigger: "blur" },
        ],
      },
      backgroundPlaceholder: "格式为院校-学历，如有多个院校则换行",
      experiencePlaceholder: "格式为公司（换行）职位（换行）工作任务",
    }
    ;
  },
  methods: {
 async requestAi(field, action) {
      // 初始化loading状态
      if (!this.loading[field]) {
        this.$set(this.loading, field, {});
      }
      this.$set(this.loading[field], action, true);
      
      try {
        // 调用后端API
        const response = await axios.post("/api/ai/process", {
          field: field,
          text: this.form[field],
          action: action
        });
        console.log(response);
              
        // 处理返回结果
        if (response.data && response.data.result) {
          this.$set(this.aiSuggestions, field, response.data.result);
          this.$message({
            message: `AI ${this.getActionName(action)}成功！`,
            type: "success",
            duration: 2000,
          });
        }
      } catch (error) {
        
        console.error("AI处理失败:", error);
        this.$message({
          message: `AI ${this.getActionName(action)}失败: ${error.response?.data?.detail || error.message}`,
          type: "error",
          duration: 3000,
        });
      } finally {
        this.$set(this.loading[field], action, false);
      }
    },
    
    getActionName(action) {
      const map = {
        polish: "润色",
        expand: "扩写",
        shrink: "缩写"
      };
      return map[action] || "处理";
    },
    
    
    applySuggestion(field, mode) {
      const suggestion = this.aiSuggestions[field];
      if (mode === "append") {
        this.form[field] += "\n" + suggestion;
      } else {
        this.form[field] = suggestion;
      }
      this.$delete(this.aiSuggestions, field);
    },
    handleAvatarSuccess(res) {
      this.form.picture = res.data;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) this.$message.error("上传头像图片只能是 JPG 格式!");
      if (!isLt2M) this.$message.error("上传头像图片大小不能超过 2MB!");
      return isJPG && isLt2M;
    },
    deleteForm() {
      const id = this.defaultForm.id;
      if (id) {
        axios
          .post(`/resume/delete/${id}`)
          .then(() => {
            this.$message({
              message: "简历删除成功！",
              type: "success",
              duration: 2000,
            });
            this.$emit("formDeleted");
          })
          .catch(() => {
            this.$message({
              message: "简历删除失败，请检查网络或稍后重试！",
              type: "error",
              duration: 2000,
            });
          });
      } else {
        this.$message({
          message: "未找到简历的 id，无法删除",
          type: "error",
          duration: 2000,
        });
      }
    },
    updateForm() {
      const resumeData = {
        ...this.form,
        abilities: this.form.abilities.split("\n"),
        experience: this.form.experience.split("\n"),
        id: this.defaultForm.id,
      };
      this.$refs.form.validate((valid) => {
        if (valid) {
          axios
            .post("http://localhost:8080/resume/update", resumeData)
            .then(() => {
              this.$message({
                message: "表单数据提交成功！",
                type: "success",
                duration: 2000,
              });
              this.$emit("formUpdated");
            })
            .catch(() => {
              this.$message({
                message: "表单数据提交失败，请检查网络或稍后重试！",
                type: "error",
                duration: 2000,
              });
            });
        }
      });
    },
  },
};
</script>

<style scoped>
.avatar-uploader.el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader.el-upload:hover {
  border-color: #409eff;
}
.ai-suggestion {
  display: flex;
  justify-content: space-between;
  background: #f5f7fa;
  padding: 10px;
  margin-bottom: 20px;
}
.ai-suggestion .original,
.ai-suggestion .suggestion {
  width: 45%;
}
.el-textarea,
.el-input {
  width: 400px;
}
</style>
